﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SportsStore.Domain.Abstract;
using SportsStore.Domain.Entities;
using SportsStore.WebUI.Models;

namespace SportsStore.WebUI.Controllers
{
    public class CartController : Controller
    {
        private IProductRepository Repository { get; set; }
        private IOrderProcessor OrderProcessor { get; set; }

        public CartController( IProductRepository repository, IOrderProcessor orderProcessor )
        {
            this.Repository = repository;
            this.OrderProcessor = orderProcessor;
        }

        public ViewResult Index( Cart cart, string returnUrl )
        {
            return this.View( new CartIndexViewModel
            {
                Cart = cart,
                ReturnUrl = returnUrl
            } );
        }

        public RedirectToRouteResult AddToCart( Cart cart, int productId, string returnUrl )
        {
            var product = this.Repository.Products
                .FirstOrDefault( item => item.ProductID == productId );

            if ( product != null )
                cart.AddItem( product, 1 );
            return this.RedirectToAction( "Index", new { returnUrl } );
        }

        public RedirectToRouteResult RemoveFromCart( Cart cart, int productId, string returnUrl )
        {
            var product = this.Repository.Products
                .FirstOrDefault( item => item.ProductID == productId );

            if ( product != null )
                cart.RemoveLine( product );
            return this.RedirectToAction( "Index", new { returnUrl } );
        }

        public PartialViewResult Summary( Cart cart )
        {
            return this.PartialView( cart );
        }

        [HttpPost]
        public ViewResult Checkout( Cart cart, ShippingDetails shippingDetails )
        {
            if ( cart.Lines.Count() == 0 )
                this.ModelState.AddModelError( "emptyCart", "Sorry, your cart is empty." );

            if ( this.ModelState.IsValid )
            {
                this.OrderProcessor.ProcessOrder( cart, shippingDetails );
                cart.Clear();
                return View( "Completed" );
            }
            
            return this.View( shippingDetails );
        }

        [HttpGet]
        public ViewResult Checkout()
        {
            return this.View( new ShippingDetails() );
        }
    }
}
